import axios from "axios";
import { Toast } from "antd-mobile";
import { LOCAL_APP_INFO } from "../utils/const";
const DEFAULT_TIMEOUT_MS = 10000; // 超时10秒

const isDev = import.meta.env?.MODE === "development";
const request = axios.create({
  baseURL: isDev ? "/api" : import.meta.env?.VITE_API_BASE,
  timeout: DEFAULT_TIMEOUT_MS,
  withCredentials: false,
  headers: {
    "Content-Type": "application/json",
  },
});

const noShowErrorMessageUrl = [
  "/member/umscbsBillCreatMemberRequest"
];

request.interceptors.request.use(
  (config) => {
    try {
      const appInfoData = JSON.parse(
        localStorage.getItem(LOCAL_APP_INFO) || "{}"
      );
      if (appInfoData?.token) {
        // 在请求体中添加token
        config.data = {
          ...config.data,
          phone: appInfoData?.phone,
          token: appInfoData?.token,
        };
        // 在请求头中添加Authorization
        config.headers = config.headers || {};
      }
    } catch (error) {
      console.log("token is not found", error);
    }
    return config;
  },
  (error) => Promise.reject(error)
);

request.interceptors.response.use(
  (response) => {
    const { config, data, status, statusText } = response;
    const showError = config?.showError !== false;
    if (status !== 200) {
      if (showError)
        Toast.show({
          content: statusText || "系统异常请联系管理员",
          icon: "fail",
          maskClickable: false,
        });
      return Promise.reject(response);
    }

    if (data && typeof data === "object" && "code" in data) {
      console.log(data, config, "----config");

      const code = data.code;
      if (code !== 0 && code !== 200) {
        if (noShowErrorMessageUrl.includes(config.url)) {
          Toast.show({
            content: "创建凭证失败请重新退出重试!",
            icon: "fail",
            maskClickable: false,
            duration: 0,
          });
          return Promise.reject(data);
        }
        if (showError)
          Toast.show({
            content: data.msg || data.message || "系统异常请联系管理员",
            icon: "fail",
            maskClickable: false,
          });
        return Promise.reject(data);
      }
      return data;
    }

    return data;
  },
  (error) => {
    const config = error?.config || {};
    const showError = config?.showError !== false;
    if (showError) {
      const message =
        error?.response?.data?.msg || error?.message || "系统异常请联系管理员";
      Toast.show({ content: message, icon: "fail", maskClickable: false });
    }
    return Promise.reject(error);
  }
);

export default request;
